<template>
  <div class="page-container">
    <a-flex :vertical="true">
      <a-card style="width: 100%;">
        <a-form ref="formRef" name="advanced_search" class="ant-advanced-search-form" :model="formState" layout="inline">
          <a-flex wrap="wrap" gap="small">
            <a-form-item name="username" label="权限名称">
              <a-input placeholder="请输入权限名称"></a-input>
            </a-form-item>

            <a-button type="primary" html-type="submit">搜索</a-button>
          </a-flex>

        </a-form>
      </a-card>

      <a-card style="width: 100%; margin: 12px 0 12px 0; min-height: calc(100vh - 250px);">
        <a-row :gutter="18">
          <a-col>
            <a-button type="primary" @click="handleAdd">新增权限</a-button>
          </a-col>
          <a-col>
            <a-button>批量删除</a-button>
          </a-col>
        </a-row>
        <br />
        <a-table :columns="columns" :data-source="permissionListData.list" bordered :row-selection="rowSelection"
                 :loading="state.loading" @resizeColumn="handleResizeColumn"
                 :pagination="{current: formState.pageNum, pageSize: formState.pageSize, onChange: (pageNum:number, pageSize:number) => {formState.pageNum = pageNum;formState.pageSize = pageSize; getPermissionsList()}, showSizeChanger: true, showQuickJumper: true, total: permissionListData.total, showTotal: (total:number) => `共${total}条`}"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'id'">
              {{ record.id || ''}}
            </template>
            <template v-if="column.key === 'password'">
              <a-space size="small">
                <a-input-password v-model:value="record.password" v-model:visible="record.visible"
                  :visibility-toggle="false" :bordered="false" />
                <a @click="record.visible = !record.visible">
                  <EyeOutlined v-if="record.visible" />
                  <EyeInvisibleOutlined v-else />
                </a>
              </a-space>
            </template>
            <template v-else-if="column.key === 'tags'">
              <span>
                <a-tag v-for="tag in record.tags" :key="tag"
                  :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'">
                  {{ tag.toUpperCase() }}
                </a-tag>
              </span>
            </template>
            <template v-else-if="column.key === 'action'">
              <span>
                <a @click="handleEdit(record)">编辑</a>
                <a-divider type="vertical" />
                <a  @click="handleDelete(record)">删除</a>
              </span>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-flex>



    <a-modal
      v-model:open="permissionModelFormState.visible"
      :title="permissionModelFormState.title"
      width="600px"
      :footer="null"
    >
      <div style="margin-top:24px">
        <a-form
          :model="permissionModelFormState.formModel"
          name="basic"
          autocomplete="off"
          size="large"
          :label-col="{ span: 4 }"
          ref="permissionFromRef"
        >
          <a-form-item
            label="权限ID"
            name="id"
            v-if="permissionModelFormState.type === 'edit'"
          >
            {{permissionModelFormState.formModel.id}}
          </a-form-item>

          <a-form-item
            label="权限标识"
            name="permissionCode"
            :rules="[{ required: true, message: '请输入权限标识' }]"
          >
            <a-input v-model:value="permissionModelFormState.formModel.permissionCode" placeholder="请输入权限标识" />
          </a-form-item>

          <a-form-item
            label="权限名称"
            name="permissionName"
            :rules="[{ required: true, message: '请输入权限名称' }]"
          >
            <a-input v-model:value="permissionModelFormState.formModel.permissionName" placeholder="请输入权限名称" />
          </a-form-item>

          <a-form-item
            label="权限描述"
            name="description"
            :rules="[{ required: true, message: '请输入权限描述' }]"
          >
            <a-textarea v-model:value="permissionModelFormState.formModel.description" placeholder="请输入权限描述" />
          </a-form-item>

          <a-form-item :wrapper-col="{ offset: 4 }" style="margin-top: 64px;margin-bottom: 32px">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-button @click="permissionFromRef.resetFields();permissionModelFormState.visible = false" :block="true">
                  取消
                </a-button>
              </a-col>
              <a-col :span="12"><a-button type="primary" block  @click="addPermissions">
                提交
              </a-button></a-col>
            </a-row>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

  </div>
</template>

<script lang="ts" setup>
import { computed, onActivated, reactive, ref } from 'vue'
import {  EyeOutlined, EyeInvisibleOutlined } from '@ant-design/icons-vue';
import { permissionsApi } from '@/api/permissions'
import notification from 'ant-design-vue/es/notification'
import type { TableColumnsType } from 'ant-design-vue'


const columns = ref<TableColumnsType>([
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    resizable: true,
    width: 80,
  },
  {
    title: '权限code',
    dataIndex: 'permissionCode',
    key: 'permissionCode',
  },
  {
    title: '权限名称',
    dataIndex: 'permissionName',
    key: 'permissionName',
  },
  {
    title: '权限描述',
    dataIndex: 'description',
    key: 'description',
    width: 200,
    resizable: true,
  },
  {
    title: '创建时间',
    key: 'createdTime',
    dataIndex: 'createdTime',
  },
  {
    title: '创建人',
    key: 'createdUserId',
    dataIndex: 'createdUserId',
  },
  {
    title: '操作',
    key: 'action',
  },
]);

function handleResizeColumn(w: number, col: any) {
  col.width = w;
}

const state = reactive<{
  selectedRowKeys: string | number[];
  loading: boolean;
}>({
  selectedRowKeys: [], // Check here to configure the default column
  loading: false,
});

const onSelectChange = (selectedRowKeys: string | number[]) => {
  console.log('selectedRowKeys changed: ', selectedRowKeys);
  state.selectedRowKeys = selectedRowKeys;
};
const rowSelection = computed(() => ({
  selectedRowKeys: state.selectedRowKeys,
  onChange: onSelectChange,
}))

const formState = reactive({
  name: '',
  pageNum: 1,
  pageSize: 10,
})


const permissionListData = reactive({
  list: [],
  total: 0,
  pages: 1,
})
const getPermissionsList = async () => {
  state.loading = true
  const res = await permissionsApi.listPermissions({
    ...formState ,
  })
  console.log(res);
  if (res?.code === 200) {
    console.log(JSON.stringify(res))
    permissionListData.total = res?.data?.total
    permissionListData.list = res?.data?.records
    permissionListData.pages = res?.data?.pages
  }
  state.loading = false
}

onActivated(() => {
  getPermissionsList()
})


const permissionFromRef = ref()
const permissionModelFormState = reactive({
  visible: false,
  formModel: {
    id: '',
    permissionName: '',
    permissionCode: '',
    description: '',
    actions: '',
  },
  title: '添加权限',
  type: 'add',
})

const addPermissions = async () => {
  permissionFromRef.value.validate().then(async () => {
    let res = null;
    if (permissionModelFormState.type === 'add') {
      res = await permissionsApi.addPermissions(permissionModelFormState.formModel)
    } else {
      res = await permissionsApi.updatePermissions(permissionModelFormState.formModel)
    }

    if (res?.code === 200) {
      notification.success({
        message: permissionModelFormState.type === 'add' ? '添加成功' : '更新成功',
      })
      permissionFromRef.value.resetFields()
      permissionModelFormState.visible = false
      getPermissionsList()
    } else {
      notification.error({
        message: res?.error || res?.message || permissionModelFormState.type === 'add' ? '添加失败' : '更新失败',
      })
      permissionModelFormState.visible = false
    }
  }).catch(() => {
    notification.error({ message: '请填写正确的数据'});
    return
  })
}

const handleDelete = async (record: any) => {
  const res = await permissionsApi.deletePermissions({id: record.id})
  if (res?.code === 200) {
    notification.success({
      message: '删除成功',
    })
    getPermissionsList()
  } else {
    notification.error({
      message: res?.message || '删除失败',
    })
  }
}

const handleEdit = async (record: any) => {
  // 编辑权限信息
  console.log(record)
  permissionModelFormState.type = 'edit'
  permissionModelFormState.formModel = record
  permissionModelFormState.title = '更新权限'
  permissionModelFormState.visible = true
}

const handleAdd = async () => {
  // 添加权限信息
  permissionModelFormState.type = 'add'
  permissionModelFormState.title = '添加权限'
  permissionModelFormState.visible = true
}

</script>

<style scoped lang="less">
.page-container {
  width: 100%;
  height: 100%;
}
</style>
